package com.express.e.root.wx.controller;

import com.express.e.root.annotation.ResponseBody;
import com.express.e.root.annotation.ResponseView;
import com.express.e.root.bean.Delivery;
import com.express.e.root.bean.Message;
import com.express.e.root.bean.User;
import com.express.e.root.enums.DeliveryEnum;
import com.express.e.root.service.ConsoleService;
import com.express.e.root.service.DeliveryService;
import com.express.e.root.service.UserService;
import com.express.e.root.service.impl.ConsoleServiceImpl;
import com.express.e.root.service.impl.DeliveryServiceImpl;
import com.express.e.root.service.impl.UserServiceImpl;
import com.express.e.root.utils.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class UserController {
    private UserService userService = new UserServiceImpl();
    private DeliveryService deliveryService = new DeliveryServiceImpl();
    private ConsoleService consoleService = new ConsoleServiceImpl();

    @ResponseBody("/wx/users/refresh.do")
    public String userRefresh(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        Integer random = RandomCodeUtil.randomGenerate();
        System.out.println("验证码："+random);
        req.getSession().setAttribute("code",random);
        RandomCodeWrap randomCodeWrap = new RandomCodeWrap(random);
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(randomCodeWrap);
        String toJson = JSONUtil.toJson(new Message(200, "验证码生成成功!", objects));
        System.out.println(toJson);
        return toJson;
    }


    @ResponseBody("/wx/users/login.do")
    public String userLoginIn(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("utf-8");
        String phone = req.getParameter("phone");
        String identifyCode = req.getParameter("identifyCode");

        /**
         * 此处插入验证码确认代码，错误则返回，正确继续
         */
        Integer s = (Integer) req.getSession().getAttribute("code");
        System.out.println(s);
        System.out.println(Integer.valueOf(identifyCode));
        if (!(s.equals(Integer.valueOf(identifyCode))||s==Integer.valueOf(identifyCode))){
            Message msg = new Message(400, "用户登陆失败，验证码不正确", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }



        User queryByPhone = userService.queryByPhone(phone);
        if (null == queryByPhone||null == queryByPhone.getUserName()){
            Message msg = new Message(400, "用户登陆失败，检查用户是否存在", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            resp.getWriter().write("<script>alert('login failed');location.href='/login.html';</script>");
            return toJson;
        }
        String userName = queryByPhone.getUserName();
        String userPwd = queryByPhone.getUserPwd();

        User user = new User();
        user.setUserName(userName);
        user.setUserPwd(userPwd);
        if (userService.userLogin(user)) {
            req.getSession().setAttribute("usersname",userName);
            req.getSession().setAttribute("userspwd",userPwd);
            List objects = new ArrayList<>();
            objects.add(user);
            Message msg = new Message(200, "用户登陆成功", objects);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            req.getSession().removeAttribute("username");
            req.getSession().removeAttribute("pwd");
            req.getSession().removeAttribute("adminName");
            req.getSession().removeAttribute("adminPwd");
            return toJson;
        }
        Message msg = new Message(400, "用户登陆失败，检查用户名与密码是否匹配", null);
        String toJson = JSONUtil.toJson(msg);
        System.out.println(toJson);
        return toJson;
    }

    @ResponseBody("/wx/users/loginOut.do")
    public String userLoginOut(HttpServletRequest req, HttpServletResponse resp){
        resp.setCharacterEncoding("utf-8");
        if (null!=req.getSession().getAttribute("usersname")){
            req.getSession().removeAttribute("usersname");
            req.getSession().removeAttribute("userspwd");
            req.getSession().setMaxInactiveInterval(1);
            Message msg = new Message(200, "用户退出成功", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        Message msg = new Message(400, "用户退出失败，用户未登陆", null);
        String toJson = JSONUtil.toJson(msg);
        System.out.println(toJson);
        return toJson;
    }

    /**
     * 用户注册，重复用户名不予注册
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/users/usersRegister.do")
    public String usersRegister(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        String pwd = request.getParameter("pwd");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String cardId = request.getParameter("cardId");
        User user = new User(
                name,
                phone,
                pwd,
                cardId,
                new Date(System.currentTimeMillis()),
                new Date(System.currentTimeMillis())
        );
        User queryByUserName = userService.queryByUserName(name);
        if (null == queryByUserName || queryByUserName.getUserId() == null) {
            User addUser = userService.addUser(user);
            ArrayList<Object> objects = new ArrayList<>();
            if (addUser.getUserId() != null) {
                UserWrap userWrap = new UserWrap(
                        addUser.getUserId(),
                        addUser.getUserName(),
                        addUser.getUserPhone(),
                        addUser.getUserPwd(),
                        FomatDateUtil.formatDate(addUser.getUserRegisterTime()),
                        FomatDateUtil.formatDate(addUser.getUserLastLoginTime()),
                        addUser.getIsSaveWeekPwd()
                );
                objects.add(userWrap);
                String toJson = JSONUtil.toJson(new Message(200, "用户注册成功", objects));
                System.out.println(toJson);
                return toJson;
            }
            String toJson = JSONUtil.toJson(new Message(400, "新增用户添加失败", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "新增用户失败，用户名已存在", null));
        System.out.println(toJson);
        return toJson;
    }


    /**
     * 根据用户快递单号，返回该快递所有信息，可以展示取件码
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/wx/users/showDeliveryCode.do")
    public String showDeliveryCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("utf-8");
        String deliveryNum = req.getParameter("deliveryNum");
        System.out.println(deliveryNum);
        if (deliveryNum.isEmpty()) {
            return JSONUtil.toJson(new Message(401, "快递单号为空！", null));
        }
        Delivery delivery = deliveryService.queryByNum(deliveryNum);

        if (null != delivery && delivery.getDeliveryAcceptor() != null  && !delivery.getDeliveryAcceptor().isEmpty()) {
            System.out.println(delivery.toString());
            DeliveryWrap deliveryWrap = new DeliveryWrap(
                    delivery.getDeliveryId(),
                    delivery.getDeliveryCode(),
                    delivery.getDeliveryCompany(),
                    delivery.getDeliveryAcceptor(),
                    delivery.getAcceptorPhone(),
                    delivery.getDeliveryNum(),
                    delivery.getDeliveryState() == 0 ? DeliveryEnum.STORE.desc : DeliveryEnum.FETCH.desc,
                    FomatDateUtil.formatDate(delivery.getStateChangeTime()));
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(deliveryWrap);
            String toJson = JSONUtil.toJson(new Message(200, "成功查寻到此快递！", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "未查到此快递！", null));
        System.out.println(toJson);
        return toJson;
    }

    /**
     * 查寻名下所有快递，区分为取件列表和未取件列表
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/users/usersList.do")
    public String myList(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        String userName = request.getParameter("userName");

        List<Delivery> queryListByName = deliveryService.queryListByName(userName);
        List<DeliveryWrap> queryListWrapper = new ArrayList<>();
        if (queryListByName != null &&  queryListByName.size()>0 ) {
            for (Delivery d :
                    queryListByName) {
                DeliveryWrap deliveryWrap = new DeliveryWrap(
                        d.getDeliveryId(),
                        d.getDeliveryCode(),
                        d.getDeliveryCompany(),
                        d.getDeliveryAcceptor(),
                        d.getAcceptorPhone(),
                        d.getDeliveryNum(),
                        d.getDeliveryState()==0?"未取件":"已取件",
                        FomatDateUtil.formatDate( d.getStateChangeTime())
                );
                queryListWrapper.add(deliveryWrap);
            }
            Object[] deliveryStreamStore = queryListWrapper.stream().filter(delivery -> delivery.getDeliveryState().equals("未取件")).toArray();
            Object[] deliveryStreamFetch = queryListWrapper.stream().filter(delivery -> delivery.getDeliveryState().equals("已取件")).toArray();
            Map<String, Object[]> hashMap = new HashMap<>();
            hashMap.put("store",  deliveryStreamStore);
            hashMap.put("fetch", deliveryStreamFetch);
            ArrayList arrayList = new ArrayList();
            arrayList.add(hashMap);
            Message msg = new Message(200, "查询到用户名下所有快递",arrayList);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        Message msg = new Message(400, "未查询到用户名下快递", queryListByName);
        String toJson = JSONUtil.toJson(msg);
        System.out.println(toJson);
        return toJson;
    }

    @ResponseBody("/wx/users/updateInfo.do")
    public String updateInfoUser(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        String msgs = request.getParameter("msg");
        System.out.println(msgs);

        Integer s = (Integer) request.getSession().getAttribute("code");
        System.out.println(s);
        System.out.println(Integer.valueOf(msgs));
        if (!(s.equals(Integer.valueOf(msgs))||s==Integer.valueOf(msgs))){
            Message msg = new Message(400, "用户验证码不正确", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }


        User queryByUserName = userService.queryByUserName((String) request.getSession().getAttribute("usersname"));
        if (queryByUserName == null||queryByUserName.getUserId()==null) {
            String toJson = JSONUtil.toJson(new Message(400, "未查询到该用户信息", null));
            System.out.println(toJson);
            return toJson;
        }
        String userName = request.getParameter("name");
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");

        System.out.println(userName);
        System.out.println(phone);

        System.out.println(queryByUserName);
        if (null != queryByUserName) {
            User userUpdate = new User(
                    queryByUserName.getUserId(),
                    userName,
                    phone,
                    password,
                    queryByUserName.getCardId(),
                    queryByUserName.getUserRegisterTime(),
                    queryByUserName.getUserLastLoginTime(),
                    queryByUserName.getIsSaveWeekPwd()
            );
            User userResult = userService.updateUser(userUpdate);
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(userResult);
            String toJson = JSONUtil.toJson(new Message(200, "修改成功", objects));
            System.out.println(toJson);
            return toJson;
        }
        return JSONUtil.toJson(new Message(400, "修改失败", null));
    }

    @ResponseBody("/wx/users/lazyListSum.do")
    public String showLazyList(HttpServletRequest req, HttpServletResponse resp){
        resp.setCharacterEncoding("utf-8");
        List<User> queryLazyList = consoleService.queryLazyList();
        if (queryLazyList != null && queryLazyList.size()>0) {
            String toJson = JSONUtil.toJson(new Message(200, "懒人总榜查询成功", queryLazyList));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "懒人总榜查询失败", queryLazyList));
        System.out.println(toJson);
        return toJson;
    }

    @ResponseBody("/wx/users/lazyListMon.do")
    public String lazyListMon(HttpServletRequest req, HttpServletResponse resp){
        resp.setCharacterEncoding("utf-8");
        List<User> queryLazyList = consoleService.queryLazyListOnMonth();
        if (queryLazyList != null && queryLazyList.size()>0) {
            String toJson = JSONUtil.toJson(new Message(200, "懒人月榜查询成功", queryLazyList));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "懒人月榜查询失败", queryLazyList));
        System.out.println(toJson);
        return toJson;
    }

    @ResponseBody("/wx/users/lazyListYear.do")
    public String lazyListYear(HttpServletRequest req, HttpServletResponse resp){
        resp.setCharacterEncoding("utf-8");
        List<User> queryLazyList = consoleService.queryLazyListOnYear();
        if (queryLazyList != null && queryLazyList.size()>0) {
            String toJson = JSONUtil.toJson(new Message(200, "懒人年榜查询成功", queryLazyList));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "懒人年榜查询失败", queryLazyList));
        System.out.println(toJson);
        return toJson;
    }


    /**
     * 用户修改密码
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/users/updateUserPwd.do")
    public String updateUserPwd(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        String oldPassword = request.getParameter("oldPassword");
        String userPassword = request.getParameter("newPassword");
        if (userPassword == null) {
            Message msg = new Message(400, "用户新密码为空", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        Integer code = Integer.valueOf(request.getParameter("code"));
        Integer code1 = (Integer) request.getSession().getAttribute("code");
        System.out.println(code);
        System.out.println(request.getSession().getAttribute("code"));
        System.out.println(!(String.valueOf(code).equals(String.valueOf(code1))));
        if (code == null || code1 == null
                || !(String.valueOf(code).equals(String.valueOf(code1)))) {
            Message msg = new Message(400, "用户验证码失败", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        String usersname = (String) request.getSession().getAttribute("usersname");
        if (usersname == null) {
            Message msg = new Message(400, "用户未登陆", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        User queryByUserName = userService.queryByUserName(usersname);
        if (!queryByUserName.getUserPwd().equals(oldPassword)) {
            Message msg = new Message(400, "用户旧密码不正确！", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        queryByUserName.setUserPwd(userPassword);
        User updateUser = userService.updateUser(queryByUserName);
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(updateUser);
        if (updateUser != null && null != updateUser.getUserId() && updateUser.getUserPwd().equals(userPassword)) {
            Message msg = new Message(200, "用户密码更新成功", objects);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        Message msg = new Message(400, "用户密码更新失败", objects);
        String toJson = JSONUtil.toJson(msg);
        System.out.println(toJson);
        return toJson;
    }



}
